package com.app.micaihu.view.login.activity

import android.annotation.SuppressLint
import android.os.Bundle
import com.app.base.BaseMvpActivity
import com.app.http.bean.BaseBean
import com.app.micaihu.R
import com.app.micaihu.bean.infor.UserInfor
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.ConfigKeyConstant
import com.app.micaihu.configure.TypeConstant
import com.app.micaihu.manager.AppConfigManager
import com.app.micaihu.manager.UserInforManager
import com.app.micaihu.view.bean.AccountConflict
import com.app.micaihu.view.login.contract.LogInContract
import com.app.micaihu.view.login.dialog.AccountConflictDialog
import com.app.micaihu.view.login.presenter.LogInPresenter
import com.app.micaihu.view.login.utils.CloseLoginActivityUtils
import com.app.micaihu.view.user.userinfo.activity.WebActivity
import com.app.micaihu.view.utils.loadCircleImage
import com.app.utils.biz.Biz
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tuo.customview.VerificationCodeView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.login_bind_phone_confirm_activity.*
import kotlinx.android.synthetic.main.login_bind_phone_confirm_activity.tvLoginCode
import kotlinx.android.synthetic.main.login_bind_phone_confirm_activity.tvPrivacyProtocol
import kotlinx.android.synthetic.main.login_bind_phone_confirm_activity.tvUserProtocol
import java.util.concurrent.TimeUnit

/**
 * 绑定手机 确认界面
 */
class BindPhoneByCodeConfirmActivity : BaseMvpActivity<LogInContract.View, LogInPresenter>(), LogInContract.View {
    override fun getPresenter() = LogInPresenter()

    override fun getLayoutId() = R.layout.login_bind_phone_confirm_activity

    override fun getBundle(bundle: Bundle) {
        phone = bundle.getString(Config.Extra.phone, "")
    }

    var phone: String = ""
    val password: String = "123456"
    private var mdDisposable: Disposable? = null


    @SuppressLint("SetTextI18n")
    override fun setData() {
        startTimer()
        tvPhone.text = phone
        tvLoginCode.postDelayed({
            KeyboardUtils.showSoftInput(verificationCodeView.editText)
        }, 500)

        val userInfoStr = Biz.instance.userInfo
        if (userInfoStr.isNotEmpty()) {
            GsonUtils.fromJson(userInfoStr, UserInfor::class.java)?.let {
                ivHead.loadCircleImage(it.headPic, R.mipmap.image_default_round)
                tvNickName.text = it.nickName
            }
        }
    }

    override fun addListeners() {
        tvLoginCode.setOnClickListener {
            mPresenter?.sendCode(phone, TypeConstant.FINDPWD_CODE)
        }

        verificationCodeView.setInputCompleteListener(object : VerificationCodeView.InputCompleteListener {
            override fun inputComplete() {
                val code = verificationCodeView.inputContent
                if (code.length == 4) {
                    //绑定手机
                    mPresenter?.boundMobile(phone, code, password)
                }
            }

            override fun deleteContent() {

            }

        })
        tvUserProtocol.setOnClickListener {
            //用户协议
            val userAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.userAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, userAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
        tvPrivacyProtocol.setOnClickListener {
            //隐私协议
            val privateAgreementUrl = AppConfigManager.getInstance().configSP.getString(ConfigKeyConstant.privateAgreementUrl, "")
            val bundle = Bundle()
            bundle.putString(Config.Extra.url, privateAgreementUrl)
            enterPager(WebActivity::class.java, bundle)
        }
    }

    @SuppressLint("SetTextI18n", "AutoDispose")
    private fun startTimer() {
        val count = 60
        mdDisposable?.dispose()
        //从1开始发射60个数字为：0-60依次输出，延时0s执行，每1s发射一次。
        mdDisposable = Flowable.intervalRange(1, count.toLong(), 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext { aLong: Long ->
                    tvLoginCode.isEnabled = false
                    tvLoginCode.text = (count - aLong).toString() + "s后重新获取"
                }.doOnComplete {
                    //倒计时完毕置为可点击状态
                    tvLoginCode.isEnabled = true
                    tvLoginCode.text = "获取验证码"
                }.subscribe()
    }

    override fun handleSendCode(result: BaseBean<Any?>?) {
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
            tvLoginCode.isEnabled = true
            tvLoginCode.text = "获取验证码"
        } else {
            if (result.isSuccess()) {
                ToastUtils.showShort("验证码已发送成功，请注意查收")
                startTimer()
            } else {
                tvLoginCode.isEnabled = true
                tvLoginCode.text = "获取验证码"
                ToastUtils.showShort(result.msg)
            }
        }
    }

    override fun handleBoundMobile(result: BaseBean<AccountConflict?>?) {
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
            mdDisposable?.dispose()
            tvLoginCode.isEnabled = true
            tvLoginCode.text = "获取验证码"
        } else {
            if (result.isSuccess()) {
                UserInforManager.getInstance().userInfor?.let {
                    it.mobile = phone
                    UserInforManager.getInstance().saveUserInfor(it)
                }
                CloseLoginActivityUtils.closeAllBindPhoneActivity()
            } else {
                val data = result.data
                if (data == null) {
                    ToastUtils.showShort(result.msg)
                } else {

                    val dialog = AccountConflictDialog(thisActivity, data)
                    dialog.show()
                    dialog.setOnClickListener(object : AccountConflictDialog.OnClickListener {
                        override fun onOk(currentSelect: Boolean) {
                            var masterUid = ""
                            var slaveUid = ""

                            if (currentSelect) {
                                data.currentUser?.let {
                                    masterUid = it.uid
                                }
                                data.clashUser?.let {
                                    slaveUid = it.uid
                                }
                            } else {
                                data.currentUser?.let {
                                    slaveUid = it.uid
                                }
                                data.clashUser?.let {
                                    masterUid = it.uid
                                }
                            }
                            mPresenter?.setMainUser(masterUid, slaveUid)
                        }

                        override fun onCancel() {
                            finish()
                        }

                    })
                }
                mdDisposable?.dispose()
                tvLoginCode.isEnabled = true
                tvLoginCode.text = "获取验证码"
            }

        }
    }

    override fun handleSetMainUser(result: BaseBean<UserInfor?>?) {
        if (result == null) {
            ToastUtils.showShort(getString(R.string.net_error))
            CloseLoginActivityUtils.closeAllBindPhoneActivity()
        } else {
            if (result.isSuccess()) {
                result.data?.let { data ->
                    //保存到本地
                    UserInforManager.getInstance().saveUserInfor(data)
                    //拉取任务数据
                    UserInforManager.getInstance().getUserTask(this, true)
                    LiveEventBus.get(Config.EventBus.loginSuccess).post(true)
                }
                CloseLoginActivityUtils.closeAllBindPhoneActivity()
            }
            ToastUtils.showShort(result.msg)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mdDisposable?.dispose()
    }
}